#!/usr/bin/python3

import tkinter as tk
from tkinter.font import Font
import os,sys
import sqlite3
from html.parser import HTMLParser
import urllib.request
import urllib.parse

class MyHTMLParser(HTMLParser):
    div=0
    count = 0
    mean=False
    a_t=False
    ol=False
    p=False
    pinyin = False
    b=False
    result=[]
    def __init__(self):
        super().__init__()
        self.result=[]
    
    def exist_attr(self, value, attrs):
        r=-1
        try:
            r=attrs.index(value)
        except:
            r=-1
        return r
        
    def handle_starttag(self, tag, attrs):
        #print("开始一个标签:",tag)
#        print()
        if tag=='a' and self.exist_attr(('name', 'maeaizbc'), attrs)>=0:
#            print(tag)
            self.a_t=True
#            for attr in attrs:
#                print("   属性值："+str(attr))
        if tag=='ol':
#            print(tag)
            self.ol=True
        if tag=='p':
#            print(tag)
            self.p=True
        if tag=='div' and self.mean is True:
            self.div += 1
        if tag=='div' and self.exist_attr( ('id', 'basicmean-wrapper'), attrs)>=0:
#            print(tag)
            self.mean=True
        if tag=='li' and self.mean is True:
            self.count += 1
        if tag=='div' and self.exist_attr(('id', 'pinyin'), attrs)>=0:
            self.pinyin = True
        if tag=='b':
            self.b=True

    def handle_endtag(self, tag):
        if tag == "a":
            self.a_t=False
            #print("结束一个标签:",tag)
        if tag=='ol':
            self.ol=False
        if tag=='p':
            self.p=False
        if tag=='div' and self.mean is True:
            self.div -= 1
            if self.div<0:
                self.mean=False
        if tag=='div':
            self.pinyin=False
        if tag=='b':
            self.b=False

    def handle_data(self, data):
        if self.a_t is True:
            self.result.append(data)
        if self.div>0 and self.ol is True and self.p is True:
            self.result.append(str(self.count)+'. '+data)
        if self.pinyin is True and self.b is True:
            self.result.append(data)

class Window:
    def __init__(self, title='输入字典项', width=800, height=600, staFunc=bool, stoFunc=bool):
        self.w = width
        self.h = height
        self.stat = True
        self.staFunc = staFunc
        self.stoFunc = stoFunc
        self.staIco = None
        self.stoIco = None
        self.root = tk.Tk(className=title)

    def center(self):
        ws = self.root.winfo_screenwidth()
        hs = self.root.winfo_screenheight()
        x = int( (ws/2) - (self.w/2) )
        y = int( (hs/2) - (self.h/2) )
        self.root.geometry('{}x{}+{}+{}'.format(self.w, self.h, x, y))   
        
    def packBtn(self):
        self.f1=tk.Frame(self.root)
        self.f2=tk.Frame(self.root)
        self.f3=tk.Frame(self.root)
        self.f1.pack(side='top')
        self.f2.pack(fill=tk.BOTH,expand=True,side='top')
        self.f3.pack(side='top')
        
        self.entry1 = tk.Entry(self.f1, font=Font(size=16))    
        self.entry1.pack(side='left')
        
        self.btnSelect=tk.Button(self.f1, command=self.baidudict, width=15, height=3)
        self.btnSelect.pack(padx=10, side='left')
        self.btnSelect['text'] = '百度字典'
             
        self.text1 = tk.Text(self.f2, width=0, height=0 , font=Font(size=16) )
        self.scroll1 = tk.Scrollbar( self.f2, width=20 )
        self.scroll1.pack(side='right', fill=tk.Y)
        self.text1.pack( fill=tk.BOTH,expand=True,side='left' )
        self.scroll1['command'] = self.text1.yview
        self.text1['yscrollcommand'] = self.scroll1.set
        
        self.btnSelect=tk.Button(self.f3, command=self.input_word, width=15, height=3)
        self.btnSelect.pack(padx=10, side='left')
        self.btnSelect['text'] = '输入文字'

        btnQuit = tk.Button(self.f3, text='关闭窗口', command=self.root.quit, width=15, height=3)
        btnQuit.pack(padx=10, side='right')
        
    def input_word(self):
        wd = self.entry1.get()
        mean = self.text1.get('0.0', tk.END)
#        print(wd) 
#        print( mean)
        db1 = sqlite3.connect( os.path.join(os.getcwd(), 'mydict.db') )
        db1.text_factory = str
        cu1 = db1.cursor()
        try:
            cu1.execute( "insert into dict(word, mean) values( ? , ? )", (wd, mean))
            self.text1.delete('1.0', tk.END)
            self.entry1.delete(0, tk.END)
        except:
            print('insert error')
        cu1.close()
        db1.commit()
        db1.close()
        
    def baidudict(self):
        self.text1.delete('0.0', tk.END)
        p=MyHTMLParser()
        p1 = urllib.parse.urlencode({'wd':self.entry1.get()})
        url1 = 'http://dict.baidu.com/s?%s' % p1
        opener = urllib.request.build_opener()
        opener.addheaders = [('User-agent', 'Mozilla/5.0')]
        fp1 = opener.open(url1)
        s = fp1.read().decode('utf-8')
        p.feed(s)
        for line in p.result:
            self.text1.insert(tk.END, line+'\n')
        

    def loop(self):
        self.root.resizable(False, False)   #禁止修改窗口大小
        self.packBtn()
        self.center()                       #窗口居中
        self.root.mainloop()

########################################################################

if __name__ == '__main__':
	cwd = os.path.split(sys.argv[0])
    os.chdir(cwd[0])
    w = Window()
    w.loop()
